package com.huaweicloud.saaslanding.install.util;

import com.huaweicloud.saaslanding.basic.exception.BizException;
import com.huaweicloud.saaslanding.basic.exception.code.ExceptionCode;
import com.huaweicloud.saaslanding.basic.utils.RegexUtil;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 配置文件校验工具类
 *
 * @since 2023-03-09
 */
@Slf4j
@Component
public class CheckYmlUtil {

    /**
     * 域名校验正则
     */
    public static final String DOMAIN_REGEX = "^((\\*\\.)?[a-zA-Z0-9][a-zA-Z0-9-]*\\.)+[a-zA-Z]{2,}$";

    @Autowired
    private Environment environment;

    public void check() {
        checkPrefixCode();
        checkDomainName();
    }

    /**
     * 校验域名
     * 至少为二级域名或泛域名
     */
    private void checkDomainName() {
        String domainName = environment.getProperty("saaslanding-install.domain.name");
        if (StringUtils.isBlank(domainName)) {
            log.error(ExceptionCode.DOMAIN_IS_NULL.getMsg());
            throw new BizException(ExceptionCode.DOMAIN_IS_NULL);
        }
        if (!domainName.matches(DOMAIN_REGEX)) {
            log.error(ExceptionCode.DOMAIN_FORMAT_INCORRECT.getMsg());
            throw new BizException(ExceptionCode.DOMAIN_FORMAT_INCORRECT);
        }

        if (!RegexUtil.checkDomainName(DomainNameUtil.getDomainName())) {
            log.error(ExceptionCode.DOMAIN_FORMAT_INCORRECT.getMsg());
            throw new BizException(ExceptionCode.DOMAIN_FORMAT_INCORRECT);
        }
    }

    /**
     * 校验企业前缀
     */
    private void checkPrefixCode() {
        String prefixCode = environment.getProperty("saaslanding-install.org.prefixCode");
        RegexUtil.checkPrefixCode(prefixCode);
    }
}
